using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp;
using Volo.Abp.Caching;
using Microsoft.Extensions.Caching.Distributed;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;

namespace CKY.AgentPlatform.Monitoring
{
    /// <summary>
    /// 监控应用服务实现
    /// </summary>
    public class MonitoringAppService : ApplicationService, IMonitoringAppService
    {
        private readonly ILogger<MonitoringAppService> _logger;
        private readonly IConfiguration _configuration;
        private readonly IDistributedCache<SystemStatus> _statusCache;
        private readonly Process _currentProcess;

        public MonitoringAppService(
            ILogger<MonitoringAppService> logger,
            IConfiguration configuration,
            IDistributedCache<SystemStatus> statusCache)
        {
            _logger = logger;
            _configuration = configuration;
            _statusCache = statusCache;
            _currentProcess = Process.GetCurrentProcess();
        }

        /// <summary>
        /// 获取系统状态
        /// </summary>
        public async Task<SystemStatus> GetSystemStatusAsync()
        {
            try
            {
                var cacheKey = "system-status";
                var cachedStatus = await _statusCache.GetAsync(cacheKey);

                if (cachedStatus != null)
                {
                    return cachedStatus;
                }

                var status = new SystemStatus
                {
                    IsHealthy = true,
                    Status = "Healthy",
                    Uptime = DateTime.UtcNow - _currentProcess.StartTime.ToUniversalTime(),
                    LastCheck = DateTime.UtcNow,
                    Version = GetApplicationVersion()
                };

                await _statusCache.SetAsync(cacheKey, status, new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30)
                });

                return status;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统状态失败");
                return new SystemStatus
                {
                    IsHealthy = false,
                    Status = "Unhealthy",
                    Uptime = TimeSpan.Zero,
                    LastCheck = DateTime.UtcNow,
                    Version = "Unknown"
                };
            }
        }

        /// <summary>
        /// 获取性能指标
        /// </summary>
        public async Task<PerformanceMetrics> GetPerformanceMetricsAsync()
        {
            try
            {
                // 使用模拟数据替代 PerformanceCounter
                var random = new Random();
                var cpuUsage = random.NextDouble() * 100;
                var memoryUsage = random.NextDouble() * 100;
                var diskUsage = random.NextDouble() * 100;

                return new PerformanceMetrics
                {
                    CpuUsage = Math.Round(cpuUsage, 2),
                    MemoryUsage = Math.Round(memoryUsage, 2),
                    DiskUsage = Math.Round(diskUsage, 2),
                    NetworkIo = GetNetworkIo(),
                    ThreadCount = _currentProcess.Threads.Count,
                    RequestQueueLength = Environment.ProcessorCount,
                    ActiveConnections = GetActiveConnections(),
                    Timestamp = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取性能指标失败");
                return GetDefaultPerformanceMetrics();
            }
        }

        /// <summary>
        /// 获取API统计信息
        /// </summary>
        public async Task<ApiStatistics> GetApiStatisticsAsync(int timeRange = 24)
        {
            try
            {
                // 返回模拟的统计数据
                // 实际项目中应该从数据库或日志中获取真实数据
                return new ApiStatistics
                {
                    TotalRequests = 15420,
                    SuccessfulRequests = 15210,
                    FailedRequests = 210,
                    AverageResponseTime = 45.6,
                    P95ResponseTime = 120.4,
                    P99ResponseTime = 256.8,
                    RequestsPerSecond = 12.3,
                    ErrorRate = 1.36,
                    TimeRange = timeRange
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取API统计信息失败");
                return new ApiStatistics();
            }
        }

        /// <summary>
        /// 获取健康检查结果
        /// </summary>
        public async Task<HealthCheckResult> GetHealthCheckAsync()
        {
            try
            {
                var checks = new List<HealthCheckItem>();

                // 检查数据库连接
                checks.Add(await CheckDatabaseConnectionAsync());

                // 检查缓存连接
                checks.Add(await CheckCacheConnectionAsync());

                // 检查磁盘空间
                checks.Add(CheckDiskSpace());

                // 检查内存使用
                checks.Add(CheckMemoryUsage());

                // 检查CPU使用
                checks.Add(CheckCpuUsage());

                var overallStatus = checks.All(c => c.Status == "Healthy") ? "Healthy" : "Unhealthy";

                return new HealthCheckResult
                {
                    OverallStatus = overallStatus,
                    Checks = checks.ToArray(),
                    CheckTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取健康检查结果失败");
                return new HealthCheckResult
                {
                    OverallStatus = "Unhealthy",
                    Checks = new[] { new HealthCheckItem { Name = "System", Status = "Unhealthy", Description = ex.Message } },
                    CheckTime = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 获取数据库性能指标
        /// </summary>
        public async Task<DatabaseMetrics> GetDatabaseMetricsAsync()
        {
            try
            {
                // 返回模拟的数据库指标
                // 实际项目中应该连接到数据库获取真实数据
                return new DatabaseMetrics
                {
                    ActiveConnections = 25,
                    IdleConnections = 10,
                    TotalConnections = 35,
                    AverageQueryTime = 12.5,
                    SlowQueries = 3,
                    QueryCacheHitRate = 0.85,
                    DatabaseSize = 1024 * 1024 * 512 // 512MB
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取数据库性能指标失败");
                return new DatabaseMetrics();
            }
        }

        /// <summary>
        /// 获取缓存性能指标
        /// </summary>
        public async Task<CacheMetrics> GetCacheMetricsAsync()
        {
            try
            {
                // 返回模拟的缓存指标
                // 实际项目中应该从缓存系统获取真实数据
                return new CacheMetrics
                {
                    TotalItems = 1250,
                    MemoryUsage = 1024 * 1024 * 50, // 50MB
                    HitRate = 0.92,
                    HitCount = 45800,
                    MissCount = 3800,
                    EvictionCount = 150,
                    AverageAccessTime = 0.8
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取缓存性能指标失败");
                return new CacheMetrics();
            }
        }

        /// <summary>
        /// 获取内存使用情况
        /// </summary>
        public async Task<MemoryUsage> GetMemoryUsageAsync()
        {
            try
            {
                // 使用模拟数据替代 PerformanceCounter
                var random = new Random();
                var availableMemory = random.Next(1000, 8000); // 1-8GB
                var totalMemory = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes;
                var usedMemory = totalMemory - (availableMemory * 1024 * 1024);

                return new MemoryUsage
                {
                    TotalMemory = totalMemory,
                    UsedMemory = usedMemory,
                    AvailableMemory = availableMemory * 1024 * 1024,
                    MemoryUsagePercentage = Math.Round((double)usedMemory / totalMemory * 100, 2),
                    Gen0Collections = GC.CollectionCount(0),
                    Gen1Collections = GC.CollectionCount(1),
                    Gen2Collections = GC.CollectionCount(2)
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取内存使用情况失败");
                return new MemoryUsage();
            }
        }

        /// <summary>
        /// 获取错误日志统计
        /// </summary>
        public async Task<ErrorStatistics> GetErrorStatisticsAsync(int timeRange = 24)
        {
            try
            {
                // 返回模拟的错误统计
                // 实际项目中应该从日志系统获取真实数据
                return new ErrorStatistics
                {
                    TotalErrors = 145,
                    FatalErrors = 2,
                    Errors = 120,
                    Warnings = 23,
                    TopErrorTypes = new[]
                    {
                        new ErrorTypeCount { ErrorType = "Timeout", Count = 45, Percentage = 31.0 },
                        new ErrorTypeCount { ErrorType = "Connection", Count = 38, Percentage = 26.2 },
                        new ErrorTypeCount { ErrorType = "Validation", Count = 28, Percentage = 19.3 },
                        new ErrorTypeCount { ErrorType = "Authentication", Count = 34, Percentage = 23.4 }
                    },
                    TimeRange = timeRange
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取错误日志统计失败");
                return new ErrorStatistics();
            }
        }

        /// <summary>
        /// 获取活跃用户统计
        /// </summary>
        public async Task<UserActivity> GetUserActivityAsync(int timeRange = 24)
        {
            try
            {
                // 返回模拟的用户活动统计
                // 实际项目中应该从用户会话或数据库获取真实数据
                return new UserActivity
                {
                    ActiveUsers = 1250,
                    NewUsers = 45,
                    TotalSessions = 3580,
                    AverageSessionDuration = 12.5,
                    PageViews = 25680,
                    TimeRange = timeRange
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取活跃用户统计失败");
                return new UserActivity();
            }
        }

        /// <summary>
        /// 获取资源使用情况
        /// </summary>
        public async Task<ResourceUsage> GetResourceUsageAsync()
        {
            try
            {
                var performanceMetrics = await GetPerformanceMetricsAsync();
                var memoryUsage = await GetMemoryUsageAsync();

                return new ResourceUsage
                {
                    Cpu = new CpuUsage
                    {
                        UsagePercentage = performanceMetrics.CpuUsage,
                        CoreCount = Environment.ProcessorCount,
                        CurrentFrequency = GetCpuFrequency(),
                        Temperature = GetCpuTemperature()
                    },
                    Memory = new MemoryUsageInfo
                    {
                        Total = memoryUsage.TotalMemory,
                        Used = memoryUsage.UsedMemory,
                        Available = memoryUsage.AvailableMemory,
                        UsagePercentage = memoryUsage.MemoryUsagePercentage
                    },
                    Disk = GetDiskUsage(),
                    Network = new NetworkUsage
                    {
                        BytesReceived = performanceMetrics.NetworkIo.BytesReceived,
                        BytesSent = performanceMetrics.NetworkIo.BytesSent
                    },
                    Timestamp = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取资源使用情况失败");
                return new ResourceUsage();
            }
        }

        /// <summary>
        /// 获取系统信息
        /// </summary>
        public async Task<SystemInfo> GetSystemInfoAsync()
        {
            try
            {
                return new SystemInfo
                {
                    OperatingSystem = RuntimeInformation.OSDescription,
                    DotNetVersion = RuntimeInformation.FrameworkDescription,
                    ApplicationVersion = GetApplicationVersion(),
                    HostName = Environment.MachineName,
                    ServerIp = GetLocalIpAddress(),
                    Uptime = DateTime.UtcNow - _currentProcess.StartTime.ToUniversalTime(),
                    StartTime = _currentProcess.StartTime.ToUniversalTime(),
                    ProcessId = _currentProcess.Id,
                    WorkingDirectory = Environment.CurrentDirectory
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统信息失败");
                return new SystemInfo();
            }
        }

        #region 私有辅助方法

        private NetworkIo GetNetworkIo()
        {
            try
            {
                var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
                var bytesReceived = 0L;
                var bytesSent = 0L;
                var packetsReceived = 0L;
                var packetsSent = 0L;

                foreach (var networkInterface in networkInterfaces)
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        var stats = networkInterface.GetIPv4Statistics();
                        bytesReceived += stats.BytesReceived;
                        bytesSent += stats.BytesSent;
                        // 使用模拟数据替代 IncomingPacketsReceived
                        packetsReceived += (long)(stats.BytesReceived / 1500); // 估算包数
                        packetsSent += stats.OutgoingPacketsDiscarded;
                    }
                }

                return new NetworkIo
                {
                    BytesReceived = bytesReceived,
                    BytesSent = bytesSent,
                    PacketsReceived = packetsReceived,
                    PacketsSent = packetsSent
                };
            }
            catch
            {
                return new NetworkIo();
            }
        }

        private int GetActiveConnections()
        {
            try
            {
                return IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections().Length;
            }
            catch
            {
                return 0;
            }
        }

        private async Task<HealthCheckItem> CheckDatabaseConnectionAsync()
        {
            var stopwatch = Stopwatch.StartNew();
            try
            {
                // 这里应该添加实际的数据库连接检查
                await Task.Delay(10); // 模拟数据库检查
                stopwatch.Stop();

                return new HealthCheckItem
                {
                    Name = "Database",
                    Status = "Healthy",
                    Description = "数据库连接正常",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                return new HealthCheckItem
                {
                    Name = "Database",
                    Status = "Unhealthy",
                    Description = $"数据库连接失败: {ex.Message}",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
        }

        private async Task<HealthCheckItem> CheckCacheConnectionAsync()
        {
            var stopwatch = Stopwatch.StartNew();
            try
            {
                // 这里应该添加实际的缓存连接检查
                await Task.Delay(5); // 模拟缓存检查
                stopwatch.Stop();

                return new HealthCheckItem
                {
                    Name = "Cache",
                    Status = "Healthy",
                    Description = "缓存连接正常",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                return new HealthCheckItem
                {
                    Name = "Cache",
                    Status = "Unhealthy",
                    Description = $"缓存连接失败: {ex.Message}",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
        }

        private HealthCheckItem CheckDiskSpace()
        {
            var stopwatch = Stopwatch.StartNew();
            try
            {
                var drive = new System.IO.DriveInfo(System.IO.Path.GetPathRoot(Environment.CurrentDirectory));
                var freeSpacePercentage = (double)drive.AvailableFreeSpace / drive.TotalSize * 100;

                stopwatch.Stop();

                return new HealthCheckItem
                {
                    Name = "Disk Space",
                    Status = freeSpacePercentage > 10 ? "Healthy" : "Warning",
                    Description = $"磁盘剩余空间: {freeSpacePercentage:F1}%",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                return new HealthCheckItem
                {
                    Name = "Disk Space",
                    Status = "Unhealthy",
                    Description = $"磁盘空间检查失败: {ex.Message}",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
        }

        private HealthCheckItem CheckMemoryUsage()
        {
            var stopwatch = Stopwatch.StartNew();
            try
            {
                // 使用模拟数据替代 PerformanceCounter
                var random = new Random();
                var memoryUsage = random.NextDouble() * 100;

                stopwatch.Stop();

                return new HealthCheckItem
                {
                    Name = "Memory",
                    Status = memoryUsage < 90 ? "Healthy" : "Warning",
                    Description = $"内存使用率: {memoryUsage:F1}%",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                return new HealthCheckItem
                {
                    Name = "Memory",
                    Status = "Unhealthy",
                    Description = $"内存检查失败: {ex.Message}",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
        }

        private HealthCheckItem CheckCpuUsage()
        {
            var stopwatch = Stopwatch.StartNew();
            try
            {
                // 使用模拟数据替代 PerformanceCounter
                var random = new Random();
                var cpuUsage = random.NextDouble() * 100;

                stopwatch.Stop();

                return new HealthCheckItem
                {
                    Name = "CPU",
                    Status = cpuUsage < 80 ? "Healthy" : "Warning",
                    Description = $"CPU使用率: {cpuUsage:F1}%",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                return new HealthCheckItem
                {
                    Name = "CPU",
                    Status = "Unhealthy",
                    Description = $"CPU检查失败: {ex.Message}",
                    Duration = stopwatch.ElapsedMilliseconds
                };
            }
        }

        private double GetCpuFrequency()
        {
            try
            {
                // 使用模拟数据替代 PerformanceCounter
                var random = new Random();
                return random.NextDouble() * 100;
            }
            catch
            {
                return 0;
            }
        }

        private double GetCpuTemperature()
        {
            try
            {
                // 获取CPU温度需要特殊的权限或第三方库
                // 这里返回默认值
                return 45.0;
            }
            catch
            {
                return 0;
            }
        }

        private DiskUsageInfo GetDiskUsage()
        {
            try
            {
                var drive = new System.IO.DriveInfo(System.IO.Path.GetPathRoot(Environment.CurrentDirectory));
                var totalSpace = drive.TotalSize;
                var usedSpace = totalSpace - drive.AvailableFreeSpace;

                return new DiskUsageInfo
                {
                    TotalSpace = totalSpace,
                    UsedSpace = usedSpace,
                    FreeSpace = drive.AvailableFreeSpace,
                    UsagePercentage = (double)usedSpace / totalSpace * 100,
                    Iops = 0 // 需要特殊权限获取
                };
            }
            catch
            {
                return new DiskUsageInfo();
            }
        }

        private string GetLocalIpAddress()
        {
            try
            {
                var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
                return "127.0.0.1";
            }
            catch
            {
                return "Unknown";
            }
        }

        private string GetApplicationVersion()
        {
            try
            {
                return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "1.0.0";
            }
            catch
            {
                return "Unknown";
            }
        }

        private PerformanceMetrics GetDefaultPerformanceMetrics()
        {
            return new PerformanceMetrics
            {
                CpuUsage = 0,
                MemoryUsage = 0,
                DiskUsage = 0,
                NetworkIo = new NetworkIo(),
                ThreadCount = 0,
                RequestQueueLength = 0,
                ActiveConnections = 0,
                Timestamp = DateTime.UtcNow
            };
        }

        #endregion
    }
}